package com.jc.subject.infra.basic.utils;

import com.alibaba.druid.filter.config.ConfigTools;

import java.security.NoSuchAlgorithmException;
import java.security.NoSuchProviderException;

/**
 * @Description: 数据库加密
 * @Author: ASL_ly
 * @Package: com.jc.subject.infra.basic.utils
 * @Project: jc-club
 * @Date: 2024/10/21  14:49
 */
public class DruidEncrypt {

    private static String publicKey  ;
    private static String privateKey ;

    static {
        try {
            String[] keyPair = ConfigTools.genKeyPair(512);
            privateKey = keyPair[0];
            System.out.println("privateKey:"+privateKey);
            publicKey = keyPair[1];
            System.out.println("publicKey:"+publicKey);
        } catch (NoSuchAlgorithmException e) {
            throw new RuntimeException(e);
        } catch (NoSuchProviderException e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * 加密方法
     * @param plainText
     * @return
     * @throws Exception
     */
    public static String encrypt(String plainText) throws Exception {
        //利用私钥加密
        String encrypt = ConfigTools.encrypt(privateKey, plainText);
        System.out.println("encrypt:"+encrypt);
        return encrypt;
    }

    /**
     * 解密方法
     * @param plainText
     * @return
     * @throws Exception
     */
    public static String decrypt(String plainText) throws Exception {
        //利用私钥解密
        String decrypt = ConfigTools.decrypt(publicKey, plainText);
        System.out.println("decrypt:"+decrypt);
        return decrypt;
    }

    public static void main(String[] args) throws Exception {
        String encrypt = encrypt("060100");
        System.out.println("encrypt:"+encrypt);

        String decrypt = decrypt(encrypt);
        System.out.println("decrypt:"+decrypt);

    }
}
